﻿using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    /// <summary>
    /// 批量删除溯源基本信息
    /// </summary>
    public class PiDelTraceabilityHandler : IRequestHandler<PiDelTraceabilityCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<TraceabilityModel> traceabilityRepo;

        public PiDelTraceabilityHandler(IBaseRepository<TraceabilityModel> traceabilityRepo)
        {
            this.traceabilityRepo = traceabilityRepo;
        }
        public Task<ApiResult<int>> Handle(PiDelTraceabilityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            int count = 0;
            foreach (var id in request.Ids)
            {
                var entity = traceabilityRepo.GetAll().FirstOrDefault(x => x.Id == id);
                if (entity!=null)
                {
                    entity.IsDelete = true;
                    traceabilityRepo.Update(entity);
                    count++;
                }
            }
            res.Code = ApiEnum.Success;
            res.Data= count;
            res.Msg = $"已成功删除{count}数据";
            return Task.FromResult(res);
        }
    }
}
